package com.xiaochun.hxhj;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.myview.CustomProgressDialog;
import com.myview.MarqueTextView;
import com.myview.MySeekBar;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ZuowenDetailActivity2 extends BaseActivity {


    private TextView tv_text;
    private int screenwidth;
    private int screenheight;
    private View view_line_bg;
    private Handler handlerdelay;
    private ScrollView scrollView;
    private long contentlength = 0;
    private String contentobj;
    private int lineHeight = 33;
    private int addcount = 1;
    private String bookid = "";
    private String id = "";
    private String bookname = "";
    private String bookauthor = "";
    private String file = "";
    private JSONArray minute_num;
    private CustomProgressDialog customProgressDialog;
    private MarqueTextView tv_titlebook;
    private LinearLayout ll_rebackf;
    private MySeekBar seek_progress;
    private int changeprogress = 0;
    private TextView tv_progress_tv;
    private PopupWindow mPopupWindowtime;
    private ImageView tv_set;
    private int num1 = 300;
    private int timeting = 1000;
    private ImageView img_start;
    private String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        tv_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                img_start.setImageResource(R.mipmap.icon_start);
                img_start.setTag(0);
                handlerdelay.removeCallbacksAndMessages(null);
                popbysettime();
            }
        });
        ll_rebackf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        img_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int tag = (int) img_start.getTag();
                if (tag == 0) {
                    img_start.setImageResource(R.mipmap.icon_stop);
                    img_start.setTag(1);
                    //字每行
                    String linenumcount = getUserInfo("linenumcount");
                    if ("".equals(linenumcount)) {
                        linenumcount = "20";
                    }
                    int num2 = Integer.parseInt(linenumcount);
                    //字每分钟  num1
                    timeting = num1 / num2;
                    timeting = timeting * 60;
                    MyLog.e("停顿时间", timeting + "    停顿时间");
                    handlerdelay.postDelayed(new Runnable() {
                        @Override
                        public void run() {


                            int[] position = new int[2];
                            view_line_bg.getLocationInWindow(position);
                            if (position[1] > screenheight / 2) {

                                int i1 = lineHeight * addcount;
                                if (i1 > tv_text.getHeight()){
                                    handlerdelay.removeCallbacksAndMessages(null);
                                    img_start.setImageResource(R.mipmap.icon_start);
                                    img_start.setTag(0);
                                    return;
                                }

                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                                int i = lineHeight + position[1];
                                layoutParams.setMargins(0, lineHeight * addcount, 0, 0);
                                view_line_bg.setLayoutParams(layoutParams);
                                addcount++;
                                scrollView.scrollBy(0, lineHeight);
                                handlerdelay.postDelayed(this, timeting);
                            } else {

                                int i1 = lineHeight * addcount;
                                if (i1 > tv_text.getHeight()){
                                    handlerdelay.removeCallbacksAndMessages(null);
                                    img_start.setImageResource(R.mipmap.icon_start);
                                    img_start.setTag(0);
                                    return;
                                }

                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                                int i = lineHeight + position[1];
                                layoutParams.setMargins(0, lineHeight * addcount, 0, 0);
                                view_line_bg.setLayoutParams(layoutParams);
                                addcount++;
                                handlerdelay.postDelayed(this, timeting);
                            }

                        }
                    }, 0);
                } else {
                    handlerdelay.removeCallbacksAndMessages(null);
                    img_start.setImageResource(R.mipmap.icon_start);
                    img_start.setTag(0);
                }

            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_freespeed;
    }

    @Override
    protected void initView() {
        changeTitle("王冰寒");
//        saveNoticeList("name", "王冰寒");
        bookid = getIntent().getStringExtra("id");
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 屏幕宽度（像素）
        screenwidth = metric.widthPixels;
        // 屏幕高度（像素）
        screenheight = metric.heightPixels;

        tv_set = findViewById(R.id.tv_set);
        tv_progress_tv = findViewById(R.id.tv_progress_tv);
        ll_rebackf = findViewById(R.id.ll_rebackf);
        scrollView = findViewById(R.id.scrollView);
        tv_titlebook = findViewById(R.id.tv_titlebook);
        tv_text = findViewById(R.id.tv_text);
        img_start = findViewById(R.id.img_start);
        img_start.setTag(0);
        view_line_bg = findViewById(R.id.view_line_bg);
        seek_progress = findViewById(R.id.seek_progress);
        seek_progress.setOnSeekBarChangeListener(mSeekBarListener);
        handlerdelay = new Handler();


        getData();


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
        layoutParams.height = lineHeight;
        int topMargin = layoutParams.topMargin;
        view_line_bg.setLayoutParams(layoutParams);
        int top = view_line_bg.getTop();


        int[] position = new int[2];
        view_line_bg.getLocationInWindow(position);
        System.out.println("getLocationInWindow:" + position[0] + "," + position[1]);

        MyLog.e("红色背景的位置", top + "=top    位置    topMargin= " + topMargin);

    }

    @Override
    protected void initData() {

    }

    private void GetByHttpClient(final String url) {
        new Thread() {
            public void run() {
                try {

                    /**
                     * OkHttpClient 的Get请求
                     */
                    //创建okHttpClient对象
                    OkHttpClient mOkHttpClient;
                    mOkHttpClient = new OkHttpClient();
                    //创建一个Request
                    final Request request = new Request.Builder()
                            .url(url)
                            .build();
                    //new call
                    Call call = mOkHttpClient.newCall(request);
                    //请求加入调度
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

//                            String str = new String(new String(response.body().bytes(), "gb2312"));
//                            String htmlStr = str;
                            String htmlStr = response.body().string();
                            MyLog.e("jorli=====>", htmlStr);
                            Message msg = new Message();
                            msg.arg1 = 10;
                            msg.obj = htmlStr;
                            if (handlerData != null) {
                                handlerData.sendMessage(msg);
                            }
                        }

                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }


    private void getData() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/index/articleDetail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("articleId", bookid);
        MyLog.e("速读详情", bookid + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handlerData.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                   /* "id": 12,
                            "name": "巴黎圣母院",
                            "image": "https://oss.bigchun.com/fastmemory/uploads/20200603/462eb8dbe419a521ea6887acca4e88cf.jpg",
                            "author": "维克多·雨果",
                            "minute_num": [
                    "约34万字"
        ],
                    "file": "https://oss.bigchun.com/fastmemory/uploads/20200603/991fa046c50fde940b59fcbc4fa3831a.txt",*/
                    id = data.getString("id");
                    bookname = data.getString("title");
                    bookauthor = data.getString("school");
                    content = data.getString("content");
//                    file = data.getString("file");
//                    minute_num = data.getJSONArray("minute_num");


                    msg.arg1 = 2;
                    handlerData.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handlerData.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handlerData.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handlerData.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 进度拖动条监听器
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarListener = new SeekBar.OnSeekBarChangeListener() {
        // 通知进度已经被修改
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                MyLog.e("进度条拖动", progress + "   进度条");
                changeprogress = progress;
            }
        }

        // 通知用户已经开始一个触摸拖动手势
        public void onStartTrackingTouch(SeekBar seekBar) {

            img_start.setImageResource(R.mipmap.icon_start);
            img_start.setTag(0);
            handlerdelay.removeCallbacksAndMessages(null);
        }

        // 通知用户触摸手势已经结束
        public void onStopTrackingTouch(SeekBar seekBar) {
            MyLog.e("进度条拖动", "   通知用户触摸手势已经结束");
            //最小300  最大5000    总长度是4700   每一个格子是47
            num1 = 47 * changeprogress;
            num1 = num1 + 300;
            int jishu = num1 / 100;
            int startnum = jishu * 100;
            int jishu2 = jishu + 1;
            int endnum = jishu2 * 100;
            tv_progress_tv.setText(startnum + "~" + endnum + "字/分钟");


        }
    };

    /**
     * 弹出搜索框
     */
    private void popbysettime() {

        // 1~100   20


        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_set_zi, null);

        EditText et_zishu = popupWindow.findViewById(R.id.et_zishu);
        TextView tv_cancle = popupWindow.findViewById(R.id.tv_cancle);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
//        et_zishu.setRegion(100, 1);
//        et_zishu.setTextWatcher();

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindowtime.dismiss();
            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_zishu.getText().toString().trim();
                if ("".equals(trim)) {
                    ToastUtils.show("请输入每行字数");
                } else {
                    saveUserInfo("linenumcount", trim + "");
                    mPopupWindowtime.dismiss();
                }
            }
        });

        mPopupWindowtime = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindowtime.getWidth();
        int mPopupWindowHeight = mPopupWindowtime.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindowtime.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindowtime.setOutsideTouchable(true);
        mPopupWindowtime.setTouchable(true);
        mPopupWindowtime.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindowtime.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowtime.showAtLocation(tv_set,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowtime.showAtLocation(tv_set,
                    Gravity.BOTTOM,
                    0,
                    0);
        }
        mPopupWindowtime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    public Handler handlerData = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    break;
                case 1:
                    ToastUtils.show(R.string.net_error);
                    break;
                case 2:
                    String num = "";
                    /*if (minute_num.length() > 0) {
                        try {
                            num = minute_num.getString(0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }*/
//                    String title = bookname + num + " 作者：" + bookauthor;
                    String title = bookname + " 出处：" + bookauthor;
                    SpannableString spanString = new SpannableString(title);
                    //再构造一个改变字体颜色的Span
                    ForegroundColorSpan span = new ForegroundColorSpan(Color.BLACK);
                    //将这个Span应用于指定范围的字体    前包括后不包括
                    spanString.setSpan(span, 0, bookname.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    AbsoluteSizeSpan spansize = new AbsoluteSizeSpan(36);
                    spanString.setSpan(spansize, 0, bookname.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_titlebook.setText(spanString);
                    /*tv_titlebook.setText(title);
                    tv_titlebook.setFocusable(true);*/
//                    GetByHttpClient(file);

                    String s = deleteHtml(content);
                    tv_text.setText(content);
                    lineHeight = tv_text.getLineHeight();
                    MyLog.e("文章内容字数", contentlength + "   字数   lineHeight=" + lineHeight);
                    view_line_bg.setVisibility(View.VISIBLE);
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String linenumcount = getUserInfo("linenumcount");
                    if ("".equals(linenumcount) || linenumcount == null) {
                        popbysettime();
                    }

                    break;
                case 3:
                    MyLog.e("上传图片异常", "上传图片异常");
                    break;
                case 4:


                    break;
                case 5:

                    break;
                case 6:

                    break;
                case 7:

                    break;
                case 8:


                    break;
                case 9:

                    break;
                case 10:
                    /*contentobj = (String) msg.obj;
                    contentlength = contentobj.length();
//                    MyLog.e("文章内容转码后",gbk+"   后");
                    tv_text.setText(contentobj);
                    lineHeight = tv_text.getLineHeight();
                    MyLog.e("文章内容字数", contentlength + "   字数   lineHeight=" + lineHeight);
                    view_line_bg.setVisibility(View.VISIBLE);
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String linenumcount = getUserInfo("linenumcount");
                    if ("".equals(linenumcount) || linenumcount == null) {
                        popbysettime();
                    }*/
                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id", "").commit();
                    sharedPreferences.edit().putString("username", "").commit();
                    sharedPreferences.edit().putString("nickname", "").commit();
                    sharedPreferences.edit().putString("mobile", "").commit();
                    sharedPreferences.edit().putString("avatar", "").commit();
                    sharedPreferences.edit().putString("score", "").commit();
                    sharedPreferences.edit().putString("student_id", "").commit();
                    sharedPreferences.edit().putString("is_bind_wx", "").commit();
                    sharedPreferences.edit().putString("token", "").commit();
                    finish();
                    break;
                case 13:

                    break;

            }

        }
    };

    public static String deleteHtml(String data) {

        try {

            String regEx_script = "<[^>]+>"; // 定义script的正则表达式

            Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);

            Matcher m_script = p_script.matcher(data);

            String txt = m_script.replaceAll(""); // 过滤script标签

            return txt;

        } catch (Exception e) {

            return "";

        }

    }


}
